package com.yzl.shiro.demo;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.junit.Test;

/**
 * 单元侧测试执行用例
 *
 * @BeforeClass->@Before->@Test->@Test->@AfterClass
 */
public class QuickStartTest5_3 {
    @Test
    public void testAuthentication() {
        //创建SecurityManager的工厂，通过配置文件ini创建
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:jdbcrealm.ini");
        SecurityManager securityManager = factory.getInstance();

        //将SecurityManager 设置到当前运行的环境中
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("jack", "123");
        subject.login(usernamePasswordToken);

        System.out.println("认证结果：" + subject.isAuthenticated());
        System.out.println("是否有对应的角色：" + subject.hasRole("role1"));
        System.out.println("getPrincipal 认证结果：" + subject.getPrincipal());
        subject.checkRole("role1");
        System.out.println("是否有视屏的发现权限：" + subject.isPermitted("video:find"));

        subject.logout();
        System.out.println("登出后的认证结果：" + subject.isAuthenticated());
    }

    @Test
    public void test2(){
        DefaultSecurityManager securityManager = new DefaultSecurityManager();

        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
        ds.setUrl("jdbc:mysql://127.0.0.1:3306/yzl_shiro?characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false");
        ds.setUsername("root");
        ds.setPassword("123456");

        JdbcRealm jdbcRealm=new JdbcRealm();
        jdbcRealm.setPermissionsLookupEnabled(true);
        jdbcRealm.setDataSource(ds);

        securityManager.setRealm(jdbcRealm);

        //将SecurityManager 设置到当前运行的环境中
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("jack", "123");
        subject.login(usernamePasswordToken);

        System.out.println("认证结果：" + subject.isAuthenticated());
        System.out.println("是否有对应的角色：" + subject.hasRole("role1"));
        System.out.println("getPrincipal 认证结果：" + subject.getPrincipal());
        subject.checkRole("role1");
        System.out.println("是否有视屏的发现权限：" + subject.isPermitted("video:delete"));

        subject.logout();
        System.out.println("登出后的认证结果：" + subject.isAuthenticated());
    }
}
